<template>
  <div>
    <el-dialog
      title="待检单详情"
      append-to-body
      destroy-on-close
      :close-on-press-escape="false"
      fullscreen
      v-if="visible"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="handleEditReset"
    >
      <div class="titleIcon">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <h4>基本信息</h4>
      </div>
      <avue-form ref="basicInfoForm" v-model="basicInfoForm" :option="basicInfoOption"></avue-form>
      <div class="titleIcon">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <h4>检验结果记录</h4>
      </div>
      <avue-form ref="inspectionResultsRecordForm" v-model="basicInfoForm" :option="inspectionResultsRecordOption" :upload-preview="uploadPreview">
        <!--      <template slot="attachments">-->
        <!--        <el-upload-->
        <!--          class="upload-demo"-->
        <!--          action="/api/blade-resource/oss/endpoint/put-file-attach"-->
        <!--          list-type="picture-card"-->
        <!--          disabled-->
        <!--          accept=".png,.jpeg,.jpg"-->
        <!--          :on-preview="handlePreview"-->
        <!--          :file-list="inspectionPictureList"-->
        <!--        >-->
        <!--          <i class="el-icon-plus"></i>-->
        <!--          <div slot="tip" class="el-upload__tip">只能上传png/jpeg/jpg文件</div>-->
        <!--        </el-upload>-->
        <!-- </div> -->
        <!--        <div v-if="dialogTitle === '详情' && JSON.stringify(form.CERT) != '[]'">-->
        <!--          <div>{{ form.CERTNAME }}</div>-->
        <!--          <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.CERT)">下载</el-button>-->
        <!--        </div>-->
        <!--      </template>-->
      </avue-form>
      <div class="titleIcon">
        <i class="el-icon-vertical-bar avue-group__icon"></i>
        <h4>异常记录</h4>
      </div>
      <avue-crud
        ref="bnormalRecordCrud"
        v-model="qmsInspectionExceptionVoListForm"
        :option="abnormalRecordOption"
        :data="basicInfoForm.qmsInspectionExceptionVoList"
        :before-open="beforeOpen"
      >
        <!--      <template slot-scope="{ row, index }" slot="menu">-->
        <!--        <el-button icon="el-icon-view" size="small" type="text" @click="abnormalRecordRowUpdate(row, 'view')">详情</el-button>-->
        <!--      </template>-->
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-delete" @click="handleEditReset">取消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      ref="dialog"
      title="查看PDF"
      append-to-body
      :visible.sync="showEsopDialog"
      :full-screen="fullScreen"
      :class="[fullScreen ? 'fullscreen' : 'no_fullScreen']"
      :close-on-click-modal="false"
      @close="fullScreen = false"
    >
      <iframe ref="pdf" :src="pdfUrl" width="100%" :height="iframeHeight"></iframe>
      <div slot="title" class="dialog-title">
        <span class="title">查看PDF</span>
        <span class="el-dialog__close fullscreen-icon" @click="fullScreen = !fullScreen">
          <i class="el-icon-full-screen"></i>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showEsopDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <doc-preview :url="fileUrl" :visiable.sync="previewVisible" :file-type="fileType"></doc-preview>
  </div>
</template>

<script>
import { getDetail } from '@/api/quality/beforePackingWaitInspect';
import DocPreview from '@/components/filePreview/docPreview';
import { downLoad } from '@/api/resource/attach';
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  components: {
    DocPreview
  },
  name: 'viewInspect',
  data() {
    return {
      fileType: '',
      fileUrl: '',
      pdfUrl: '',
      previewVisible: false,
      showEsopDialog: false,
      fullScreen: '',
      basicInfoForm: {},
      basicInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        column: [
          {
            label: '检验单号',
            prop: 'documentNo',
            span: 8,
            disabled: true
          },
          {
            label: '检验类型',
            prop: 'sourceTypeName',
            span: 8,
            value: '包装前检验',
            disabled: true
          },
          {
            label: '客户名称',
            prop: 'partnerName',
            span: 8,
            disabled: true
          },
          {
            label: '物料编码',
            prop: 'partNo',
            span: 8,
            disabled: true
          },
          {
            label: '物料名称',
            prop: 'partName',
            span: 8,
            disabled: true
          },
          {
            label: '产品型号',
            prop: 'partModel',
            span: 8,
            disabled: true
          },
          {
            label: '生产工单',
            prop: 'sourceNo',
            span: 8,
            disabled: true
          },
          {
            label: '工单数量',
            prop: 'workOrderQuantity',
            span: 8,
            disabled: true
          },
          {
            label: '生产产线',
            prop: 'lineName',
            span: 8,
            disabled: true
          },
          {
            label: '报检时间',
            prop: 'createTime',
            span: 8,
            disabled: true
          },
          {
            label: '是否加急',
            prop: 'isUrgent',
            span: 8,
            type: 'select',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            disabled: true
          },
          {
            label: '检验人员',
            prop: 'examineByName',
            type: 'search',
            span: 8,
            disabled: true
          }
        ]
      },
      inspectionResultsRecordForm: {},
      qmsInspectionExceptionVoListForm: {},
      inspectionResultsRecordOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        column: [
          {
            label: '综合判断',
            prop: 'examineResult',
            span: 8,
            type: 'select',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择 综合判断',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不合格数量',
            prop: 'ngQuantity',
            span: 8,
            disabled: true
          },
          {
            label: '查看检验报告',
            prop: 'attachments',
            type: 'upload',
            dataType: 'object',
            disabled: true,
            row: true,
            span: 24,
            propsHttp: {
              url: 'link',
              name: 'originalName',
              res: 'data'
            },
            rules: [
              {
                required: true,
                message: '请上传检验报告',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            disabled: true,
            span: 24,
            maxRows: 3,
            minRows: 3
          }
        ]
      },
      abnormalRecordData: [],
      abnormalRecordOption: {
        height: '300',
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: true,
        menu: true,
        refreshBtn: false,
        columnBtn: false,
        labelWidth: 150,
        column: [
          {
            label: '产品序列号',
            prop: 'objectNo'
          },
          {
            label: '不良现象',
            prop: 'ngFailureName'
          },
          {
            label: '不良原因（大类）',
            prop: 'ngMainCauseName'
          },
          {
            label: '不良原因（小类）',
            prop: 'ngSubCauseName'
          },
          {
            label: '不良说明',
            prop: 'faultDescription'
          },
          {
            label: '改善措施',
            prop: 'improvementMeasure'
          },
          {
            label: '备注',
            prop: 'remark',
            span: 24
          },
          {
            label: '附件',
            prop: 'img',
            type: 'upload',
            dataType: 'string',
            listType: 'picture-card',
            span: 24,
            hide: true
          }
        ]
      },
      inspectionPictureList: []
    };
  },
  computed: {
    iframeHeight() {
      const docHeight = document.documentElement.clientHeight;
      const iframeHeight = docHeight - 188 + 'px';
      return this.fullScreen ? iframeHeight : '600px';
    }
  },
  methods: {
    async getData(id) {
      try {
        const res = await getDetail(id);
        const data = res.data.data;
        this.basicInfoForm = data;
        this.basicInfoForm.attachments =
          (data.qmsInspectionAttachmentList.length &&
            data.qmsInspectionAttachmentList.map((item) => ({
              value: item.link,
              label: item.attachmentName
            }))) ||
          [];
        this.basicInfoForm.examineBy = this.basicInfoForm.examineBy ? this.basicInfoForm.examineBy : JSON.parse(localStorage.getItem('saber-userInfo')).content.user_id;
        this.basicInfoForm.examineByName = this.basicInfoForm.examineByName
          ? this.basicInfoForm.examineByName
          : JSON.parse(localStorage.getItem('saber-userInfo')).content.user_name;
        console.log(data);
      } catch (e) {
        console.log(e);
      } finally {
      }
    },
    handleEditReset() {
      this.inspectionPictureList = [];
      this.$emit('update:visible', false);
      this.$emit('closeDialog');
    },
    handlePreview(file) {
      let url = this._get(file, 'response.data.link', '');
      this.$ImagePreview([{ url: url ? url : file.url }], 0, {
        closeOnClickModal: false
      });
    },
    beforeOpen(done, type) {
      try {
        this.qmsInspectionExceptionVoListForm.img = this.qmsInspectionExceptionVoListForm.qmsInspectionAttachmentList.map((item) => item.link).join(',');
      } catch (e) {
        this.qmsInspectionExceptionVoListForm.img = '';
      }
      done();
    },
    getFileType(url) {
      // 从URL中提取文件名
      const filename = url.split('/').pop();
      // 提取文件名的扩展名
      const fileExtension = filename.split('.').pop();
      return fileExtension;
    },
    handleFullScreen() {
      this.fullScreen = !this.fullScreen;
    },

    uploadPreview(file, column, done) {
      let url = this._get(file, 'response.data.link', '');
      if (url) {
        file.url = url;
      }
      const fileType = this.getFileType(file.url);
      if (['doc', 'docx', 'xlsx', 'xls'].includes(fileType)) {
        this.previewVisible = true;
        this.fileUrl = file.url;
        this.fileType = fileType;
        return;
      }
      if (file.url.indexOf('pdf') != -1) {
        downLoad({ link: file.url }).then(
          (res) => {
            let fileURL = null;
            var blob = new Blob([res.data], { type: 'application/pdf' });
            if (window.createObjectURL != undefined) {
              // basic
              fileURL = window.createObjectURL(blob);
            } else if (window.webkitURL != undefined) {
              // webkit or chrome
              try {
                fileURL = window.webkitURL.createObjectURL(blob);
              } catch (error) {
                console.log(error);
              }
            } else if (window.URL != undefined) {
              // mozilla(firefox)
              try {
                fileURL = window.URL.createObjectURL(blob);
              } catch (error) {
                console.log(error);
              }
            }
            this.pdfUrl = '/pdf/web/viewer.html?file=' + encodeURIComponent(fileURL);
            this.showEsopDialog = true;
          },
          (error) => {}
        );
      } else {
        if (this.isImageFile(url || file.url)) {
          this.$ImagePreview([{ url: url ? url : file.url }], 0, {
            closeOnClickModal: false
          });
        } else {
          window.open(url || file.url);
        }
      }
    },
    isImageFile(filename) {
      let ext = filename.split('.').pop().toLowerCase();
      return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext);
    }
  }
};
</script>

<style lang="scss" scoped>
.titleIcon {
  display: flex;
  align-items: center;
}
::v-deep .avue-crud__menu {
  display: none;
}

.dialog-title {
  position: relative;
  .title {
    display: inline-block;
  }
  .fullscreen-icon {
    position: absolute;
    right: 20px;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    color: #909399;
    &:hover {
      color: #0a84ff;
    }
  }
}

.fullscreen {
  ::v-deep .el-dialog {
    width: 100%;
    margin: 0 !important;
    margin-top: 0vh !important;
  }
}
.no_fullScreen {
  ::v-deep.el-dialog {
    width: 50%;
    margin-top: 5vh !important;
  }
}
</style>
